package com.System.servlet;

import com.System.pojo.User;
import com.System.service.Login;
import com.System.service.LoginImpl.LoginService;
import com.System.untils.SaltMD5Util;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;


@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    Login service=new LoginService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println(username);
        String password = request.getParameter("password");
        System.out.println(password);
        String number = request.getParameter("remember");

        User user;

        User result = service.selectPasswordByUserName(new User(username, password));
        if(result==null){
            request.setAttribute("login_msg","用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request,response);
            return;
        }
        String resultPassWord = result.getPassWord();
        try {
            user = service.login(new User(username,password));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (SaltMD5Util.verifySaltPassword(password, resultPassWord)){
            if ("1".equals(number)) {
                //创建Cookie
                Cookie c_username = new Cookie("username", username);
                //设置存活时间
                c_username.setMaxAge(60 * 60 * 24 * 7);
                //发送
                response.addCookie(c_username);
            }
            //利用session将user数据共享给selectAll请求，因为session能够让两个请求共享数据
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            //获取虚拟路径就可以使其具有多用性
            request.setAttribute("username",username);
            System.out.println("执行了");

            response.sendRedirect("http://localhost:8080/BarSystem/User.html?username="+username);

        } else {
            request.setAttribute("login_msg","用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
